package com.test.jwtlogin.controller;

import com.alibaba.fastjson.JSONObject;
import com.test.jwtlogin.annotation.NotDuplicate;
import com.test.jwtlogin.annotation.UserLoginToken;
import com.test.jwtlogin.entity.User;
import com.test.jwtlogin.enums.PwEnum;
import com.test.jwtlogin.service.TokenService;
import com.test.jwtlogin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserController {

//    public static final String PW = "123456";

    @Autowired
    private UserService userService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        User user1 = userService.findById(user.getId());
        JSONObject jsonObject = new JSONObject();
        if (user1 == null) {
            jsonObject.put("message", "登录失败，用户不存在");
            return jsonObject;
        } else {
            if (!String.valueOf(PwEnum.ORIGINAL_PW.getCode()).equals(user1.getPassword())) {
                jsonObject.put("message", "登录失败，密码错误");
                return jsonObject;
            } else {
                String token = tokenService.getToken(user);
                jsonObject.put("token", token);
                jsonObject.put("user", user1);
                return jsonObject;
            }
        }
    }

    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage() {
        return "你已通过验证";
    }

    @GetMapping("/duplicate")
    @NotDuplicate
    public String duplicate() {
        return "duplicate";
    }
}
